import React, { Component } from 'react'
import { fetchData  } from "../AjaxConsumer";
import { Tree, Spin, Modal } from 'antd';
import Actions from '../../actions';
import store from '../../stores'
const TreeNode = Tree.TreeNode;

export default class TreeComponent extends Component {

    constructor(props) {
        super(props);
        this.state = {
            expandedKeys: this.props.expandedKeys ? this.props.expandedKeys : [],
            autoExpandParent: true,
            checkedKeys: this.props.checkedKeys ? this.props.checkedKeys : [],
            selectedKeys: this.props.selectedKeys ? this.props.selectedKeys : [],
            resData: null,
            storeResData: null,

        }
    }
    //和stroes进行通信挂钩 并绑定解绑事件unsubscribe
    unsubscribe = store.listen((resData)=>{

    })
    //组件销毁时解绑与stores的监听
    componentWillUnmount(){
          this.unsubscribe();
    }
    //请求书，刷新函数
    refleshData = () => {
        //发送ajax请求基础树数据
        // Actions.wmsAjax(this.props.url,'post',null);
        let options = {
            url: this.props.url,        //请求地址
            type: 'post',    //请求方式
            condition: {}, 
        };
        fetchData(this, options, (resData) => {
            this.setState({
                storeResData: resData,
                selectedKeys: []
            });
        });
    }
    componentDidMount(){
        this.refleshData();
    }
    //展开/收起节点时触发
    onExpand = (expandedKeys) => {
        this.setState({
            expandedKeys,
            autoExpandParent: false,
        });
    }
    //点击复选框触发
    onCheck = (checkedKeys,info) => {
        // console.log('checkedKeys===', checkedKeys);
        //let tempCheckedKeys = [...checkedKeys,...info.halfCheckedKeys];
        this.setState({
            checkedKeys: checkedKeys,
            halfCheckedKeys: info.halfCheckedKeys,
            //parentKeys: info.halfCheckedKeys,
            selectedKeys: [],
        });
        if (this.props.handCheckedKeys) {
            this.props.handCheckedKeys(checkedKeys, info.halfCheckedKeys);
        }

    }
    //拿到树顶级节点的ID数组
    getTopTreeId = () => {
        let treeId = this.props.treeId;
        let treeChildren = this.props.treeChildren;
        let storeResData = this.state.storeResData.data;
        let topTreeId = [];
        storeResData.map((item) => {
            topTreeId.push(item[treeId]);
        })
        return topTreeId;
    }
    //点击树节点触发
    onSelect = (selectedKeys, info) => {
        let topTreeId = [];
        topTreeId = this.getTopTreeId();
        //检查是否需要进行ajax请求，若是顶级ID，则不进行请求
        let IsSendAjax = true;
        for(let i = 0; i < topTreeId.length; i++){
            // console.log('topTreeId',topTreeId[i])
            // console.log('selectedKeys',selectedKeys[i])
            if(selectedKeys == topTreeId[i]){
                IsSendAjax = false;
            }
        }
        //只要点击就让selectedKeys有值，既而发送ajax请求（目的：修改antd组件自带的选择，和再点击取消选择）
        if (selectedKeys.length == 0){
            selectedKeys = this.state.selectedKeys;
        }
        //若需要发送请求，且selectedKeys条件不为空
        if(IsSendAjax == true && selectedKeys.length > 0){
            let treeName = this.props.treeName;
            //如果父级页面有titleClick={true}，才进行点击title发送ajax
            if (this.props.titleClick){
                this.props.loading(true); //loading画面设置
                this.setState({ selectedKeys:selectedKeys});
                // Actions.wmsSendAjax(this.props.titleClickUrl+selectedKeys,'get');
                let options = {
                    url: this.props.titleClickUrl+selectedKeys,      //请求地址
                    type: 'get',    //请求方式
                    condition: {}   //请求条件
                };
                fetchData(this, options, (resData) => {
                    this.setState({
                        resData: resData
                    });
                    // let selectedKeys = this.state.selectedKeys;
                    let selectedName = this.state.resData.data[treeName];
                    //右侧页面更新form
                    if(this.props.upDataForm){
                        this.props.upDataForm(resData,selectedKeys,selectedName,info); 
                    }
                });
            }
        }
        
    }
    componentWillReceiveProps(nextProps) {

        this.setState({
            checkedKeys: nextProps.checkedKeys,
        });
    }
    render() {
        let gData = this.state.storeResData ? this.state.storeResData.data : null;
        let treeId = this.props.treeId;
        let treeName = this.props.treeName;
        let treeChildren = this.props.treeChildren;
        let targetc = this.state.checkedKeys
        let dataArrId = [];
        let loop2 = (data, dataArrId, parentID) => {
            data.map((item) => {
                if (item.children) {
                    let childIds = [];
                    let keyId = item.id;

                    item.children.map( (e) => {
                        childIds.push(e.id);
                    });
                    if(typeof(parentID) == "undefined"){
                        parentID = -1;
                    }
                    dataArrId.push({
                        key: keyId,
                        value: childIds,
                        parentID: parentID
                    })

                    loop2(item.children, dataArrId, keyId)
                }
            });
        }
        if (this.props.checkable){
            if(gData!=null){
                loop2(gData, dataArrId);
            }
            //得到半选
            let halfIds = gethalfIds(dataArrId, targetc);
            //总数据targetc去掉半选
            let tempA, tempB;
            for (let i = targetc.length - 1; i >= 0; i--) {
                tempA = targetc[i];
                for (let j = halfIds.length - 1; j >= 0; j--) {
                    tempB = halfIds[j];
                    if (tempA == tempB) {
                        targetc.splice(i, 1);
                        halfIds.splice(j, 1);
                        break;
                    }
                }
            }

        }
        let loop = data => data.map((item) => {
            if (item[treeChildren]) {

                return (
                    <TreeNode key={item[treeId]} title={item[treeName]}>
                        {loop(item[treeChildren])}
                    </TreeNode>
                );
            }
            return <TreeNode key={item[treeId]} title={item[treeName]} />;
        });
        let myTree;
        if(gData != null){
            myTree =  <Tree
                            checkable = {this.props.checkable ? true : false}
                            onCheck={this.onCheck}
                            onSelect={this.onSelect}
                            selectedKeys={this.state.selectedKeys}
                            checkedKeys = {this.state.checkedKeys}
                            defaultExpandedKeys = {this.getTopTreeId()}
                        >
                            {loop(gData)}
                        </Tree>
        } else {
            myTree = <Spin size="large" />
        }


        return(
                <div>{myTree}</div>
        )
    }
}
function gethalfIds(dataArrId, checkIds) {
    var myMap = new Map();
    dataArrId.map( (item) => {
        let key = item.key;
        let parentID = item.parentID;
        let value = item.value;
        let size = value.length;
        let forSize = 0;
        value.map( (e) => {
            let index = checkIds.indexOf(e);
            if(index < 0){
                forSize += 1;
            }
        });
        if(size != forSize){
            myMap.set(key, parentID);
        }
    });
    let halfIds = [], halfParentIds = [];
    for(let [key, value] of myMap) {
        halfIds.push(key);
        if(halfParentIds.indexOf(value) < 0){
            halfParentIds.push(value);
        }
    }
    halfParentIds.map( (halfItem) => {
        dataArrId.map( (item) => {
            let key = item.key;
            if(key == halfItem){
                let value = item.value;
                let size = value.length;
                value.map( (e) => {
                    let index = halfIds.indexOf(e);
                    if(index > -1){
                        if(halfIds.indexOf(key) < -1){
                            halfIds.push(key);
                        }
                    }
                });
            }
        });
    });
    return halfIds;
}
